package problem10;

//10.正则表达式匹配
//https://leetcode.cn/problems/regular-expression-matching/description/

class Solution {
    public boolean isMatch(String s, String p) {
        s = " " + s;
        p = " " + p;
        int n = s.length(), m = p.length();
        boolean[][] dp = new boolean[n][m];
        for(int j = 2; j<m; j+=2) {
            if(p.charAt(j) == '*') dp[0][j] = true;
            else break;
        }
        dp[0][0] = true;
        for(int i = 1; i<n; i++) {
            for(int j = 1; j<m; j++) {
                if(s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') dp[i][j] = dp[i-1][j-1];
                else if(p.charAt(j) == '*') {
                    if(p.charAt(j-1) == '.') dp[i][j] = dp[i][j-2] || dp[i-1][j];
                    else dp[i][j] = dp[i][j-2] || (s.charAt(i) == p.charAt(j-1) && dp[i-1][j]);
                }
            }
        }
        return dp[n-1][m-1];
    }
}

/*
dp[i][j]: s的前i个字符能否匹配p的钱j个字符

*/